//
//  WYJHomeTableViewController.swift
//  MySinaWeibo
//
//  Created by believewilliam on 16/9/24.
//  Copyright © 2016年 believewilliam. All rights reserved.
//

import UIKit
import SVProgressHUD
import YYModel
class WYJHomeTableViewController: WYJBaseTableViewController {
    // 微博视图模型属性
    lazy var homeViewModel: WYJHomeViewModel = WYJHomeViewModel()
    // 小菊花视图
    lazy var indicatorView: UIActivityIndicatorView = {
        let indicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.gray)
        
        return indicator
    }()
    // 下拉刷新的tipLabel
    private lazy var tipLabel: UILabel = {
        let l = UILabel(title: "", textColor: UIColor.white, fontSize: 14)
        l.textAlignment = .center
        l.backgroundColor = UIColor.orange
        l.frame = CGRect(x: 0, y: 29, width: screenWidth, height: 35)
        l.isHidden = true
        return l
    }()
    // 自定义下拉刷新控件
    private lazy var MyRefreshControl: WYJRefreshControl = WYJRefreshControl()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        if userLogin == false {
            self.visitorView.updateInfo(tipText: "关注一些人,快回到这里看看有什么惊喜", imageName: nil)
            return
        }
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop", target: self, action: #selector(push))
        setupTableView()
        loadData()
    }
    // 获取微博数据
    func loadData() {
//        print("loadData")
        // 如果tipLabel正在动画时，又下拉刷新了，此时要防止tipLabel的再次开始动画
        if self.tipLabel.isHidden == false {
            // 停止下拉刷新动画
//            self.refreshControl?.endRefreshing()
            self.MyRefreshControl.endRefreshing()
            return
        }
        homeViewModel.loadData(isPullUp: indicatorView.isAnimating, finished: { (success, newStatusCount) in
            // 不管向服务器请求数据成功与否，都应该停止上拉加载更多的小菊花动画和下拉刷新动画
            // 停止下拉刷新动画
//            self.refreshControl?.endRefreshing()
            self.MyRefreshControl.endRefreshing()
            
            if success != true {
                // 停止上拉加载更多的小菊花动画
                self.indicatorView.stopAnimating()
                SVProgressHUD.showError(withStatus: errorTip)
                return
            }
            // 如果是下拉刷新，开始tipLabel的动画
            if !(self.indicatorView.isAnimating) {
                self.startTipLabelAnimation(newStatusCount: newStatusCount)
            }
            // 停止上拉加载更多的小菊花动画
            self.indicatorView.stopAnimating()
            // 刷新数据
            self.tableView.reloadData()
        })
      
        
    }
    
    private func startTipLabelAnimation(newStatusCount: Int) {
        self.tipLabel.isHidden = false
        self.tipLabel.text = newStatusCount == 0 ? "没有新的微博" : "有\(newStatusCount)条新的微博"
        UIView.animate(withDuration: 1, animations: {
            self.tipLabel.frame.origin.y = 64
            }, completion: { (_) in
                //                    print(Thread.current)
                UIView.animate(withDuration: 1, delay: 1, options: [], animations: {
                    self.tipLabel.frame.origin.y = 29
                    }, completion: { (_) in
                        //                          print(Thread.current)
                        self.tipLabel.isHidden = true
                })
        })

    }
    
    func setupTableView() {
        // 注册原创微博cell所在的nib
        tableView.register(UINib(nibName: "WYJStatusTableViewCell", bundle: nil), forCellReuseIdentifier: "WYJStatusTableViewCell")
        // 再注册转发微博cell所在的nib
        tableView.register(UINib(nibName: "WYJRetweetedStatusCell", bundle: nil), forCellReuseIdentifier: "WYJRetweetedStatusCell")
        tableView.rowHeight = 360
        tableView.separatorStyle = .none
        tableView.tableFooterView = indicatorView
        /*
        // 使用系统刷新控件
        refreshControl = UIRefreshControl()
        refreshControl?.addTarget(self, action: #selector(loadData), for: .valueChanged)
        */
        // 使用自定义刷新控件
        MyRefreshControl.addTarget(self, action: #selector(loadData), for: .valueChanged)
        self.view.addSubview(MyRefreshControl)
        // 使用KVO机制，添加观察者
        self.tableView.addObserver(MyRefreshControl, forKeyPath: "contentOffset", options: .new, context: nil)
        // 添加刷新提示label
        self.navigationController?.view.insertSubview(self.tipLabel, belowSubview: self.navigationController!.navigationBar)
    }
    
    @objc private func push() {
        
        let tempVC = WYJTempViewController()
        self.navigationController?.pushViewController(tempVC, animated: true)
    }
    
}

// 实现数据源方法和代理方法
extension WYJHomeTableViewController {
    
    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return homeViewModel.statusViewModelArray.count
    }
    override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        if indexPath.row == homeViewModel.statusViewModelArray.count-2 && indicatorView.isAnimating == false {
            indicatorView.startAnimating()
//            print("上拉加载更多数据")
            loadData()
        }
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let viewModel = homeViewModel.statusViewModelArray[indexPath.row]
        let cellId = viewModel.statusModel?.retweeted_status == nil ? "WYJStatusTableViewCell" : "WYJRetweetedStatusCell"
        let statusCell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! WYJStatusTableViewCell
        
        // 视图绑定模型
        statusCell.statusViewModel = viewModel
        //        print(viewModel.statusModel?.pic_urls?.last?.thumbnail_pic)
        return statusCell
    }
    // 确定每一行的高度
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let viewModel = homeViewModel.statusViewModelArray[indexPath.row]
        let cellId = viewModel.statusModel?.retweeted_status == nil ? "WYJStatusTableViewCell" : "WYJRetweetedStatusCell"
        let nibName = cellId == "WYJStatusTableViewCell" ? "WYJStatusTableViewCell" : "WYJRetweetedStatusCell"
        let cell = UINib(nibName: nibName, bundle: nil).instantiate(withOwner: nil, options: nil).last as!WYJStatusTableViewCell
        cell.statusViewModel = viewModel
        cell.layoutIfNeeded()
        
        return cell.toolBar.frame.maxY
    }
}
